<template>
  <view>
    <view class="search-box">
      <uni-search-bar :value="keywords" @confirm="search" @input="input" placeholder="请输入搜索内容" cancelButton="none"
        radius=15 :focus="true " />
    </view>

    <view class="suggest_list" v-if="keywords!==''&& searchResults.length!==0">
      <view class="suggest_item" v-for="item in searchResults" :key="item.goods_id" @click="gotoDetail(item)">
        <view class="goods_name">
          {{item.goods_name}}
        </view>
        <uni-icons type="arrowright" size="16"></uni-icons>
      </view>
    </view>

    <view class="history_box" v-else>
      <view class="history_title">
        <text>搜索记录</text>
        <uni-icons type="trash" size="20" @click="historyClearHandler()"></uni-icons>
      </view>
      <view class="history_list">
        <view class="history_item" v-for="(item,index) in histories" :key="index" @click="historyClickHandler(item)">
          <uni-tag :text="item" size="default" circle inverted type="default">
          </uni-tag>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
  export default {
    data() {
      return {
        timer: null,
        keywords: '',
        searchResults: [],
        //搜索历史
        historyList: []
      };

    },
    methods: {
      search() {

      },
      input(e) {
        clearTimeout(this.timer)

        this.timer = setTimeout(() => {
          this.keywords = e;
          this.getSearchList()
        }, 500)
      },
      async getSearchList() {
        if (this.keywords.length === 0) {
          this.searchResults = []
          return;
        }
        const {
          data: res
        } = await uni.$http.get('/api/public/v1/goods/qsearch', {
          query: this.keywords
        })
        this.searchResults = res.message;
        this.saveSearchHistory()
      },
      gotoDetail(item) {
        uni.navigateTo({
          url: '/subpkg/goods_detail/goods_detail?goods_id=' + item.goods_id
        })
      },
      historyClickHandler(item) {
        // this.keywords = item;
        // setTimeout(() => {
        //   clearTimeout(this.timer)
        // }, 200)
        // this.getSearchList()
        uni.navigateTo({
          url: '/subpkg/goods_list/goods_list?query=' + item
        })
      },
      saveSearchHistory() {
        // this.historyList.push(this.keywords)
        //使用set集合去重
        const set = new Set(this.historyList);
        //先删除再添加的作用是：保证输入相同的关键词时
        //不重复且更新到最近一次的搜索记录
        set.delete(this.keywords)
        set.add(this.keywords)
        //使用from方法把集合转为数组
        this.historyList = Array.from(set)

        //将搜索历史持久化存储到本地
        uni.setStorageSync('history', JSON.stringify(this.historyList))
      },
      historyClearHandler() {
        let _this = this;
        uni.showModal({
          title: '删除全部历史记录',
          success(res) {
            if (res.confirm) {
              _this.historyList = []
              uni.setStorageSync('history', '[]')

            }
          }
        })

      }
    },
    computed: {
      histories() {
        return [...this.historyList].reverse()
      }
    },
    onLoad() {
      this.historyList = JSON.parse(uni.getStorageSync('history') || '[]')
    }
  }
</script>

<style lang="scss" scoped>
  .search-box {
    position: sticky;
    top: 0;
    z-index: 999;
    background-color: #C00000;
  }

  .suggest_list {
    padding: 0 10rpx;

    .suggest_item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 26rpx 10rpx;
      font-size: 30rpx;
      border-bottom: 5rpx solid #efefef;



      .goods_name {
        //文字不允许换行
        white-space: nowrap;
        //溢出部分隐藏
        overflow: hidden;
        //文本溢出后，使用...代替
        text-overflow: ellipsis;
        margin-right: 10rpx;
      }
    }
  }

  .history_box {
    padding: 0 20rpx;

    .history_title {
      display: flex;
      justify-content: space-between;
      font-size: 30rpx;
      font-weight: bold;
      padding: 20rpx 0;
      border-bottom: 5rpx solid #efefef;
    }

    .history_list {
      display: flex;
      justify-content: flex-start;
      flex-wrap: wrap;

      .history_item {
        margin: 20rpx 20rpx;
      }
    }
  }
</style>
